package com.lovesher.payment.service.resposity.base;

import java.util.List;

import com.lovesher.payment.common.resposity.base.Page;
import com.lovesher.payment.common.resposity.base.Pageable;
import com.lovesher.payment.common.resposity.search.BaseSearch;

/**
 * BaseDao的MyBatis实现
 * 
 * 
 * @param <T>
 */
@SuppressWarnings("rawtypes")
public abstract class DaoDefault<T, M extends Mapper> implements DaoBase<T> {

	public abstract M getMapper();

	/**
	 * 
	 * 查询（根据主键ID查询）
	 * 
	 **/
	@Override
	@SuppressWarnings("unchecked")
	public T selectById(Long id) {
		return (T) this.getMapper().selectById(id);
	}

	/**
	 * 
	 * 删除（根据主键ID删除）
	 * 
	 **/
	@Override
	public int deleteById(Long id) {
		return this.getMapper().deleteById(id);
	}

	/**
	 * 
	 * 添加
	 * 
	 **/
	@Override
	@SuppressWarnings("unchecked")
	public T insert(T record) {
		Long resultCode = this.getMapper().insert(record);
		if (resultCode <= 0) {
			return null;
		}
		return record;
	}

	/**
	 * 
	 * 修改
	 * 
	 **/
	@Override
	@SuppressWarnings("unchecked")
	public int update(T record) {
		return this.getMapper().update(record);
	}

	/**
	 * 
	 * 通用查询
	 * 
	 */
	@Override
	@SuppressWarnings("unchecked")
	public Page<T> findPage(Pageable pageable) {
		List<T> list = getMapper().findList(pageable);
		Integer count = getMapper().countForList(pageable);
		Page<T> page = new Page<T>(list, count, pageable);
		page.setTotal(count);
		page.setTotalPages((int) Math.ceil((double) count / (double) page.getPageSize()));
		page.setPageNumber(pageable.getPageNumber());
		return page;
	}
	
	@Override
	public Integer countPage(Pageable pageable) {
		Integer count = getMapper().countForList(pageable);
		return count;
	}

	/**
	 * 
	 * 批量删除
	 * 
	 */
	@Override
	public void removeBeans(Long[] ids) {
		for (int i = 0; i < ids.length; i++) {
			this.getMapper().deleteById(ids[i]);
		}
	}
	
	/**
	 * 
	 * 查询所有
	 * 
	 */
	@Override
	@SuppressWarnings("unchecked")
	public List<T> findAll() {
		return getMapper().findAll();
	}
	
	@SuppressWarnings("unchecked")
	public Page<T> findPageByBaseSearch(Pageable pageable,BaseSearch bean) {
		List<T> list = getMapper().findListByBaseSearch(pageable,bean);
		Integer count = getMapper().countByBaseSearch(pageable,bean);
		Page page = new Page(list,count,pageable);
		return page;
	}
	
	@Override
	public Integer count() {
    	return getMapper().count();
    }
	
	/**
	 * 
	 * 查询（根据主键ID查询）
	 * 
	 **/
	@Override
	@SuppressWarnings("unchecked")
	public T selectByUserId(Long userId) {
		return (T) this.getMapper().selectByUserId(userId);
	}
}
